package logic

import (
	"context"
	"strconv"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"2106A-zg6/baidu/srv/internal/svc"
	"2106A-zg6/baidu/srv/models"
	"2106A-zg6/baidu/srv/pb/baidu"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *baidu.LoginRequest) (*baidu.LoginResponse, error) {

	login, err := models.UserLogin(in.UserName, in.Password)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, err.Error())
	}

	return &baidu.LoginResponse{
		UserInfo: ModelRespLogin(login),
	}, nil
}

func ModelRespLogin(u models.User) *baidu.User {
	return &baidu.User{
		Id:           int64(u.ID),
		Username:     u.Username,
		Password:     u.Password,
		Mobile:       u.Mobile,
		Email:        u.Email,
		UserBalance:  u.UserBalance,
		UserIntegral: strconv.FormatInt(u.UserIntegral, 10),
	}
}
